var cccCurrentTheme = {
    General: {
        background: '#FFF',
        borderWidth: '6px',
        borderColor: '#e0e6ef',
        borderRadius: '0 0 0 0',
        textColor: '#000',
        showExport: false
    },
    Tabs: {
        borderColor: '#d7d7d7',
        activeBorderColor: '#ffcd04',
    },
    Chart: {
        animation: false,
        fillColor: 'rgba(151,187,205,0.2)',
        borderColor: '#97BBCD',
    },
    Conversion: {
        background: 'transparent',
        lineHeight: '20px',
        color: '#000',
    }
};

if (typeof cccTheme !== 'undefined') {
    for (var key in cccCurrentTheme) {
        var group = cccCurrentTheme[key];
        for (var prop in group) {
            if (!group.hasOwnProperty(prop)) continue;
            if (cccTheme.hasOwnProperty(key) && cccTheme[key].hasOwnProperty(prop)) {
                cccCurrentTheme[key][prop] = cccTheme[key][prop];
            }
        }
    }
}

if (typeof cccThemeV3Chart !== 'undefined') {
    for (var key in cccCurrentTheme) {
        var group = cccCurrentTheme[key];
        for (var prop in group) {
            if (!group.hasOwnProperty(prop)) continue;
            if (cccThemeV3Chart.hasOwnProperty(key) && cccThemeV3Chart[key].hasOwnProperty(prop)) {
                cccCurrentTheme[key][prop] = cccThemeV3Chart[key][prop];
            }
        }
    }
}

function cccCreateCSSSelector(selector, styleRules) {
    var style = document.createElement('style');
    style.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(style);
    if (!(style.sheet || {}).insertRule) {
        (style.styleSheet || style.sheet).addRule(selector, styleRules);
    } else {
        style.sheet.insertRule(selector + "{" + styleRules + "}", 0);
    }
}

var cccglobal_data = {};
var cccupdating = false;
var cccloading_counter = 0;
var cccfsym = 'BTC';
var ccctsym = 'USD';
var cccscale = 'histohour';
var ccclimit = '120';
var cccperiod = '1M';
var cccaggregate = '6';
var cccminPeriod = '6hh';
var cccforceAll = 'false';
var cccchart_type = 'candle';
var chartBTC;

var colors = [
    '#5cb85c',
    '#A11B0A',
    '#006098',
    '#F89017',
    '#000000',
    '#398439'
];

function validateCheckboxes(event, target) {
    var marketsContainer = document.getElementById('marketsContainer' + ccctsym);
    var childs = marketsContainer.childNodes;
    var result = false;

    for (var i = 0; i < childs.length; i++) {
        var checkbox = childs[i].getElementsByTagName("input")[0];

        if (checkbox.checked && target !== checkbox) {
            result = true;
        }
    }

    if (!result) {
        event.preventDefault();
    }
}

function cccUpdateChart(externalCCCTsym) {
    if (typeof externalCCCTsym != 'undefined') {
        ccctsym = externalCCCTsym;
    }
    if (cccchart_type == 'line') {
        var marketsContainer = document.getElementById('marketsContainer' + ccctsym);
    } else if (cccchart_type == 'candle' || cccchart_type == 'ohlc') {
        var marketsContainer = document.getElementById('marketsContainerCandle' + ccctsym);
    }

    var childs = marketsContainer.childNodes;
    var unloaded_markets = [];
    var selected_markets = [];
    cccupdating = true;

    if (cccglobal_data[ccctsym] === undefined) {
        cccglobal_data[ccctsym] = {};
    }

    if (cccglobal_data[ccctsym][cccperiod] === undefined) {
        cccglobal_data[ccctsym][cccperiod] = {};
    }

    for (var i = 0; i < childs.length; i++) {
        var checkbox = childs[i].getElementsByTagName("input")[0];
        if (checkbox.checked) {
            selected_markets.push({Name: checkbox.value, Color: childs[i].style.color});
            if (cccglobal_data[ccctsym][cccperiod][checkbox.value] === undefined) {
                unloaded_markets.push(checkbox.value);
            } else if (new Date().getTime() - cccglobal_data[ccctsym][cccperiod][checkbox.value].timeout.getTime() > (1000 * 60 * 5)) {
                unloaded_markets.push(checkbox.value);
            }
        }
    }

    if (unloaded_markets.length > 0) {
        for (var i = 0; i < unloaded_markets.length; i++) {
            finish = (i == unloaded_markets.length - 1);

            loadData(unloaded_markets[i], selected_markets);
        }
        loading_counter = unloaded_markets.length;
    } else if (selected_markets.length > 0) {
        cccRedrawChart(selected_markets);
        cccupdating = false;
    }
}

function cccRedrawChart(selected_markets) {
    var dataSets = [];
    var fillAlphas = 0.4;
    var maxPoints = 400;
    for (var i = 0; i < selected_markets.length; i++) {
        var newChartData = [];
        var data = cccglobal_data[ccctsym][cccperiod][selected_markets[i].Name].data;
        for (var k = 0; k < data.length; k++) {
            var point = data[k];
            newChartData.push({
                'date': new Date(point.time),
                'close': point.close,
                'high': point.high,
                'low': point.low,
                'open': point.open,
                'volume': point.volumeto
            });
        }
        maxPoints = Math.max(maxPoints, newChartData.length);
        if (cccchart_type == 'line') {
            dataSets[i] = {
                "title": ToSymbolsDisplay[ccctsym],
                "color": selected_markets[i].Color,
                "fieldMappings": [{
                    "fromField": "close",
                    "toField": "close"
                }, {
                    "fromField": "volume",
                    "toField": "volume"
                }],
                "dataProvider": newChartData,
                "categoryField": "date"
            }

            if (i > 0) {
                dataSets[i].compared = true;
            }
        } else if (cccchart_type == 'candle' || cccchart_type == 'ohlc') {
            dataSets[i] = {
                "title": ToSymbolsDisplay[ccctsym],
                "color": selected_markets[i].Color,
                "fieldMappings": [{
                    "fromField": "close",
                    "toField": "close"
                },
                    {
                        "fromField": "open",
                        "toField": "open"
                    },
                    {
                        "fromField": "high",
                        "toField": "high"
                    },
                    {
                        "fromField": "low",
                        "toField": "low"
                    },
                    {
                        "fromField": "volume",
                        "toField": "volume"
                    }],
                "dataProvider": newChartData,
                "categoryField": "date"
            }
        }
    }

    if (dataSets.length > 1) {
        fillAlphas = 0;
    }

    var graphs;
    if (cccchart_type == 'line') {
        graphs = [{
            "id": "g1",
            "lineThickness": "2",
            "fillAlphas": fillAlphas,
            "valueField": "close",
            "comparable": true,
            "compareField": "close",
            "compareGraphLineThickness": 2,
            "balloonText": "[[title]] [[close]]",
            "compareGraphBalloonText": "[[title]] [[close]]"
        },
            {
                "id": "g2",
                "lineThickness": "2",
                "fillAlphas": 1,
                "valueField": "close",
                "hidden": "false",
                "visibleInLegend": false
            }];
    } else if (cccchart_type == 'candle' || cccchart_type == 'ohlc') {
        graphs = [{
            "type": 'candlestick',
            "id": "g1",
            "openField": "open",
            "closeField": "close",
            "highField": "high",
            "lowField": "low",
            "valueField": "close",
            "lineColor": "#5cb85c",
            "fillColors": "#5cb85c",
            "negativeLineColor": "#A11B0A",
            "negativeFillColors": "#A11B0A",
            "fillAlphas": 1,
            "balloonText": "<b>Open:</b> [[open]] <br /> <b>High:</b> [[high]] <br /> <b>Low:</b> [[low]] <br /> <b>Close:</b> [[close]]",
            "useDataSetColors": false,
            "proCandlesticks": false
        },
            {
                "id": "g2",
                "lineThickness": "2",
                "fillAlphas": 1,
                "valueField": "close",
                "hidden": "true",
                "visibleInLegend": false
            }
        ];

        if (cccchart_type == 'ohlc') {
            graphs[0].type = 'ohlc';
            graphs[0].lineThickness = 2;
        }
    }
    var currentChartObject = {
        "type": "stock",
        "pathToImages": "https://www.cryptocompare.com/images/",
        "theme": "light",
        "dataSets": dataSets,
        "panels": [{
            "title": "Value",
            "showCategoryAxis": true,
            "recalculateToPercents": "never",
            "percentHeight": 70,
            "stockGraphs": graphs,
            "stockLegend": {
                "periodValueTextComparing": "[[value.close]]",
                "periodValueTextRegular": "[[value.close]]"
            }
        }, {
            "title": "Volume",
            "percentHeight": 30,
            "stockGraphs": [{
                "valueField": "volume",
                "type": "column",
                "showBalloon": false,
                "fillAlphas": 1
            }],
            "stockLegend": {
                "periodValueTextRegular": "[[value.close]]"
            }
        }
        ],

        "chartScrollbarSettings": {
            "enabled": true,
            "graph": "g2",
            "graphType": "line",
            "updateOnReleaseOnly": true,
            "oppositeAxis": false,
            "backgroundColor": "#444",
            "backgroundAlpha": 0.7,
            "graphFillAlpha": 0.5,
            "graphLineAlpha": 0.5,
            "selectedBackgroundColor": "#ffffff",
            "selectedBackgroundAlpha": 0.4,
            "selectedGraphFillAlpha": 0,
            "selectedGraphLineAlpha": 1,
            "autoGridCount": true,
            "gridAlpha": 0.15,
            "height": 30
        },

        "categoryAxesSettings": {
            "minPeriod": cccminPeriod,
            "maxSeries": maxPoints + 50
        },

        "export": {
            "enabled": true,
            "menu": [],
            "libs": {"autoLoad": false}
        },

        "chartCursorSettings": {
            "valueBalloonsEnabled": true,
            "fullWidth": true,
            "cursorAlpha": 0.1,
            "valueLineBalloonEnabled": true,
            "valueLineEnabled": true,
            "valueLineAlpha": 0.5
        }
    };
    chartBTC = AmCharts.makeChart('cccChartDiv' + 'BTC', currentChartObject);
}

function loadData(market, selected_markets) {
    var url = 'https://min-api.cryptocompare.com/data/' + cccscale + '?aggregate=' + cccaggregate + '&e=' + market + '&fsym=' + cccfsym + '&limit=' + ccclimit + '&tsym=' + ccctsym + '&extraParams=widget';
    if (cccforceAll == true) {
        url = 'https://min-api.cryptocompare.com/data/' + cccscale + '?aggregate=' + cccaggregate + '&e=' + market + '&fsym=' + cccfsym + '&allData=' + cccforceAll + '&tsym=' + ccctsym + '&extraParams=widget';
    }

    var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    var loader = document.getElementById('loaderccc');
    loader.style.display = 'block';

    xhr.open('get', url, true);
    xhr.onreadystatechange = function () {
        var status;
        var data;

        if (xhr.readyState == 4) {
            status = xhr.status;
            if (status == 200) {
                data = JSON.parse(xhr.responseText);
                loading_counter--;

                for (var i = 0; i < data.Data.length; i++) {
                    data.Data[i].time = data.Data[i].time * 1000;
                }

                cccglobal_data[ccctsym][cccperiod][market] = {data: data.Data, timeout: new Date()};

                if (loading_counter == 0) {
                    cccupdating = false;
                    loader.style.display = 'none';

                    cccRedrawChart(selected_markets);
                }
            } else {
                // pass
            }
        }
    };
    xhr.send();
}

if (cccCurrentTheme.General.showExport) {
    function openLightBoxExport() {
        document.body.appendChild(lightboxBg);
        window.getComputedStyle(lightboxBg).opacity;
        lightboxBg.classList.add("in");

        document.body.appendChild(exportLightBoxContainer);
        window.getComputedStyle(exportLightBox).transform;
        exportLightBox.classList.add("fade");
    }

    function removeExportLightBoxContainer() {
        document.body.removeChild(exportLightBoxContainer);
        exportLightBox.removeEventListener("transitionend", removeExportLightBoxContainer);
    }

    function removeLightBoxBg() {
        document.body.removeChild(lightboxBg);
        lightboxBg.removeEventListener("transitionend", removeLightBoxBg);
    }

    function closeLightBoxExport() {
        exportLightBox.classList.remove("fade");
        lightboxBg.classList.remove("in");

        exportLightBox.addEventListener("transitionend", removeExportLightBoxContainer);
        lightboxBg.addEventListener("transitionend", removeLightBoxBg);
    }

    function exportFinal() {
        if (typeof cccSendEmailAddressToServer !== 'undefined') {
            var email = document.getElementById('ccc_export_email').value;
            var patt = new RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/);

            if (patt.test(email)) {
                chartBTC.export.capture({}, function () {
                    this.toPNG({multiplier: 2}, function (data) {
                        this.download(data, this.defaults.formats.PNG.mimeType, "cryptocompareChart.png");
                    });
                });
                cccSendEmailAddressToServer(email);
            } else {
                alert('Incorrect email. Please try again!');
            }
            closeLightBoxExport();
        } else {
            chartBTC.export.capture({}, function () {
                this.toPNG({multiplier: 2}, function (data) {
                    this.download(data, this.defaults.formats.PNG.mimeType, "cryptocompareChart.png");
                });
            });
        }
    }

    /* Export Lighbox */

    cccCreateCSSSelector('.exportLightBoxContainer', 'z-index: 999; max-height: 100%; position: fixed; top: 0; left: 0; bottom: 0; right: 0;');
    cccCreateCSSSelector('.exportLightBox', 'min-height: 330px; background: #FFF url(\'\') center bottom no-repeat; padding: 15px; transform: translate(0, 0); transition: transform 0.3s ease-out, opacity 0.15s linear; opacity: 0; width: 570px; position: relative; top: 0; left: 50%; margin-left: -300px; border: 6px solid #ffcd04;');
    cccCreateCSSSelector('.exportLightBox.fade', 'transform: translate(0px, 100px); opacity: 1;');
    cccCreateCSSSelector('.lightboxBg', 'z-index: 998; max-height: 100%; background: #000; position: fixed; top: 0; left: 0; bottom: 0; right: 0;');
    cccCreateCSSSelector('@media (max-width: 767px)', '.exportLightBox { width: auto; margin-left: 10px; margin-right: 10px; left: 0;}');

    cccCreateCSSSelector('.fade-bg', 'opacity: 0; transition: opacity 0.15s linear;');
    cccCreateCSSSelector('.fade-bg.in', 'opacity: 0.3;');

    var exportLightBoxContainer = document.createElement("div");
    exportLightBoxContainer.className = 'exportLightBoxContainer';
    exportLightBoxContainer.onclick = closeLightBoxExport;
    var exportLightBox = document.createElement("div");
    exportLightBox.className = 'exportLightBox';
    exportLightBox.onclick = function (event) {
        event.stopPropagation();
    }

    cccCreateCSSSelector('.exportBtnFinal', 'display: block; clear: both; font-size: 18px; height: 40px; color: rgb(255, 205, 4); line-height: 40px; background: #000; width: 120px; text-align: center; border-radius: 20px; float: right; margin-top: 20px;');
    cccCreateCSSSelector('.exportBtnFinal:hover', 'cursor: pointer; color: #000; background: rgb(255, 205, 4);');
    cccCreateCSSSelector('.exportHeader', 'overflow: auto;');
    cccCreateCSSSelector('.exportHeader span', 'padding-bottom: 6px; color: #27282d; font-size: 16px; border-bottom: 2px solid #ffcd04; float: left;');
    cccCreateCSSSelector('.exportHeader a.close-icon', 'float: right; font-size: 23px; font-weight: 600; color: #ccc; margin-top: -6px; ');
    cccCreateCSSSelector('.exportHeader a.close-icon:hover', 'cursor: pointer; color: #666;');

    cccCreateCSSSelector('.exportForm', 'overflow: hidden; padding: 60px 30px; padding-left: 90px; color: #555;');
    cccCreateCSSSelector('@media (max-width: 767px)', '.exportForm { padding: 30px; }');
    cccCreateCSSSelector('.exportForm label', 'outline: none; font-size: 16px; line-height: 36px; width: 100%; margin-right: 15px;');
    cccCreateCSSSelector('.exportForm input', 'float: left; outline: none; padding: 6px 12px; width: 100%; font-size: 16px; color: #939496; border: 1px solid #cccccc; height: 36px; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); margin-bottom: 20px;');
    cccCreateCSSSelector('.exportForm select', 'float: left; outline: none; width: 100%; font-size: 16px; color: #939496; 1px solid #cccccc; background: #fff; height: 36px; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);');

    var cccBuildFormForExportEmailCaputure = '<div class="exportHeader"><span>History data export</span><a class="close-icon" onclick="closeLightBoxExport()">��</a></div><div class="exportForm">';
    if (typeof cccSendEmailAddressToServer !== 'undefined') {
        cccBuildFormForExportEmailCaputure += '<label for="ccc_export_email">Your Email:</label><input type="text" id="ccc_export_email" class="exportInput" />';
    }
    ;
    cccBuildFormForExportEmailCaputure += '<label for="export_format" style="clear:both;">Export as:</label><select id="export_format"><option value="PNG">PNG</option></select><a class="exportBtnFinal" onclick="exportFinal()">Export</a></div>';

    exportLightBox.innerHTML = cccBuildFormForExportEmailCaputure;
    var lightboxBg = document.createElement("div");
    lightboxBg.className = 'lightboxBg fade-bg';

    exportLightBoxContainer.appendChild(exportLightBox);
}

var embedable = document.createElement("div");
var embedableInfo = document.createElement("div");

/* Chart Container */

var containerCanvas = document.createElement("div");
containerCanvas.id = 'cccChartDiv' + 'BTC';
containerCanvas.style.height = '500px';
containerCanvas.style.marginTop = '10px';

embedable.className = "ccc-widget ccc-chart-v3";

embedableInfo.style.background = cccCurrentTheme.General.background;
embedableInfo.style.textAlign = "left";
embedableInfo.style.border = cccCurrentTheme.General.borderWidth + ' solid ' + cccCurrentTheme.General.borderColor;
embedableInfo.style.padding = "15px";
embedableInfo.style.color = cccCurrentTheme.General.textColor;
embedableInfo.style.position = 'relative';

/* Tabs */

cccCreateCSSSelector('.active', 'border-color: ' + cccCurrentTheme.Tabs.activeBorderColor + ' !important');
cccCreateCSSSelector('.tablinks', 'border: 2px solid ' + cccCurrentTheme.Tabs.borderColor + '; padding: 0 5px; margin: 5px 4px; cursor: pointer; font-size: 18px; font-weight: 600; display: block; float: left;');
cccCreateCSSSelector('.tablinks:hover', 'border-color: ' + cccCurrentTheme.Tabs.activeBorderColor);

var tabsContainer = document.createElement("div");
tabsContainer.style.overflow = 'auto';
tabsContainer.className = 'tabContainer';

var ToSymbolsDisplay = [];

ToSymbolsDisplay['USD'] = '$';
tabElemUSD = document.createElement('a');

tabElemUSD.id = 'tabElemUSD';
tabElemUSD.className = 'tablinks';

tabElemUSD.className = 'tablinks active';

tabElemUSD.innerHTML = '比特币';
tabsContainer.appendChild(tabElemUSD);
embedableInfo.appendChild(tabsContainer);

cccCreateCSSSelector('.tabcontent', 'justify-content: space-between; flex-wrap: wrap; ');

/* Markets Line */

cccCreateCSSSelector('.cccCustomRadioContainer input[type="checkbox"]', 'display: none;');
cccCreateCSSSelector('.cccCustomRadioContainer', 'padding-left: 19px; padding-right: 10px; padding-top: 2px; padding-bottom: 2px; line-height: 16px;');
cccCreateCSSSelector('.cccCustomRadioContainer label', 'position: relative;');
cccCreateCSSSelector('.cccCustomRadioContainer span.checkbox:hover', 'cursor: pointer; ');
cccCreateCSSSelector('.cccCustomRadioContainer span::before', 'content: \'\'; position: absolute; top: 0; bottom: 0; margin: auto;');
cccCreateCSSSelector('.cccCustomRadioContainer span::after', 'content: \'\'; position: absolute; top: 0; bottom: 0; margin: auto;');
cccCreateCSSSelector('.cccCustomRadioContainer span.checkbox::before', 'width: 15px; height: 15px; background-color: #fff; left: -19px; box-sizing: border-box; border: 1px solid #ccc; transition: border-color .2s;');
cccCreateCSSSelector('.cccCustomRadioContainer span.checkbox::after', 'opacity: 0; content: \'\'; position: absolute; width: 7px; height: 3px; background: transparent; top: -1; left: -16px; border: 2px solid #333; border-top: none; border-right: none; -ms-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); transform: rotate(-45deg);');
cccCreateCSSSelector('.cccCustomRadioContainer input[type="checkbox"]:checked + label span.checkbox::after', 'opacity: 1;');

cccCreateCSSSelector('@media (max-width: 767px)', '.cccCustomRadioContainer { padding-left: 38px; line-height: 32px; }');

cccCreateCSSSelector('@media (max-width: 767px)', '.cccCustomRadioContainer span.checkbox::before { width: 30px; height: 30px; left: -38px;}');
cccCreateCSSSelector('@media (max-width: 767px)', '.cccCustomRadioContainer span.checkbox::after { width: 9px; height: 5px; top: -1; left: -28px; }');


var marketsContainerCandleUSD = document.createElement("div");
marketsContainerCandleUSD.id = 'marketsContainerCandleUSD';
marketsContainerCandleUSD.className = 'tabcontent';
marketsContainerCandleUSD.style.display = 'none';
marketsContainerCandleUSD.style.overflow = 'auto';
marketsContainerCandleUSD.style.margin = '15px 4px';

var marketElemCandleUSDIndex = document.createElement("div");
marketElemCandleUSDIndex.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="Index_USD_radio" name="USD_radio" value="CCCAGG" onchange="cccUpdateChart()" checked><label for="Index_USD_radio"><span class="radio">Index</span></label></div>';
marketElemCandleUSDIndex.style.color = colors[0];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDIndex);


var marketElemCandleUSDCoinbase = document.createElement("div");
marketElemCandleUSDCoinbase.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="Coinbase_USD_radio" name="USD_radio" value="Coinbase" onchange="cccUpdateChart()"><label for="Coinbase_USD_radio"><span class="radio">Coinbase</span></label></div>';
marketElemCandleUSDCoinbase.style.color = colors[1];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDCoinbase);

var marketElemCandleUSDBitstamp = document.createElement("div");
marketElemCandleUSDBitstamp.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="Bitstamp_USD_radio" name="USD_radio" value="Bitstamp" onchange="cccUpdateChart()"><label for="Bitstamp_USD_radio"><span class="radio">Bitstamp</span></label></div>';
marketElemCandleUSDBitstamp.style.color = colors[2];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDBitstamp);

var marketElemCandleUSDKraken = document.createElement("div");
marketElemCandleUSDKraken.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="Kraken_USD_radio" name="USD_radio" value="Kraken" onchange="cccUpdateChart()"><label for="Kraken_USD_radio"><span class="radio">Kraken</span></label></div>';
marketElemCandleUSDKraken.style.color = colors[3];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDKraken);

var marketElemCandleUSDlmax = document.createElement("div");
marketElemCandleUSDlmax.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="lmax_USD_radio" name="USD_radio" value="lmax" onchange="cccUpdateChart()"><label for="lmax_USD_radio"><span class="radio">lmax</span></label></div>';
marketElemCandleUSDlmax.style.color = colors[4];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDlmax);

var marketElemCandleUSDBitfinex = document.createElement("div");
marketElemCandleUSDBitfinex.innerHTML = '<div class="cccCustomRadioContainer"><input type="radio" id="Bitfinex_USD_radio" name="USD_radio" value="Bitfinex" onchange="cccUpdateChart()"><label for="Bitfinex_USD_radio"><span class="radio">Bitfinex</span></label></div>';
marketElemCandleUSDBitfinex.style.color = colors[5];

marketsContainerCandleUSD.appendChild(marketElemCandleUSDBitfinex);


embedableInfo.appendChild(marketsContainerCandleUSD);


/* Tabs Periods*/

var optionsContainer = document.createElement("div");

cccCreateCSSSelector('.tabperiods', 'display: block; float: left; font-size: 12px; text-align: center; margin-right: 5px; line-height: 22px; width: 54px; height: 22px; background: #f7f7f7');
cccCreateCSSSelector('.tabperiods:hover', 'background: #e7e7e7');
cccCreateCSSSelector('.tabperiods_active', 'background: #e7f0f9; font-weight: 600;');
cccCreateCSSSelector('.tabsPeriodsContainer', 'float: left; margin-top: 9px;');

var tabsPeriodsContainer = document.createElement("div");
tabsPeriodsContainer.style.overflow = 'auto';
tabsPeriodsContainer.style.margin = '5px 4px;';
tabsPeriodsContainer.className = 'tabsPeriodsContainer';
tabsPeriodsContainer.style.display = "none"

tabPeriodElem1D = document.createElement('a');


tabPeriodElem1D.className = 'tabperiods';

tabPeriodElem1D.style.cursor = 'pointer';
tabPeriodElem1D.innerHTML = '1D';
tabPeriodElem1D.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histominute';
        ccclimit = '96';
        cccperiod = '1D';
        cccaggregate = '15';
        cccminPeriod = '15mm';
        cccforceAll = false;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElem1D);

tabPeriodElem1W = document.createElement('a');


tabPeriodElem1W.className = 'tabperiods';

tabPeriodElem1W.style.cursor = 'pointer';
tabPeriodElem1W.innerHTML = '1W';
tabPeriodElem1W.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histohour';
        ccclimit = '168';
        cccperiod = '1W';
        cccaggregate = '1';
        cccminPeriod = 'hh';
        cccforceAll = false;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElem1W);

tabPeriodElem1M = document.createElement('a');


tabPeriodElem1M.className = 'tabperiods tabperiods_active';

tabPeriodElem1M.style.cursor = 'pointer';
tabPeriodElem1M.innerHTML = '1M';
tabPeriodElem1M.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histohour';
        ccclimit = '120';
        cccperiod = '1M';
        cccaggregate = '6';
        cccminPeriod = '6hh';
        cccforceAll = false;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElem1M);

tabPeriodElem3M = document.createElement('a');


tabPeriodElem3M.className = 'tabperiods';

tabPeriodElem3M.style.cursor = 'pointer';
tabPeriodElem3M.innerHTML = '3M';
tabPeriodElem3M.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histoday';
        ccclimit = '90';
        cccperiod = '3M';
        cccaggregate = '1';
        cccminPeriod = 'DD';
        cccforceAll = false;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElem3M);

tabPeriodElem1Y = document.createElement('a');


tabPeriodElem1Y.className = 'tabperiods';

tabPeriodElem1Y.style.cursor = 'pointer';
tabPeriodElem1Y.innerHTML = '1Y';
tabPeriodElem1Y.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histoday';
        ccclimit = '365';
        cccperiod = '1Y';
        cccaggregate = '1';
        cccminPeriod = 'DD';
        cccforceAll = false;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElem1Y);

tabPeriodElemALL = document.createElement('a');


tabPeriodElemALL.className = 'tabperiods';

tabPeriodElemALL.style.cursor = 'pointer';
tabPeriodElemALL.innerHTML = 'ALL';
tabPeriodElemALL.onclick = function (event) {
    if (!cccupdating) {
        cccscale = 'histoday';
        ccclimit = '2000';
        cccperiod = 'ALL';
        cccaggregate = '1';
        cccminPeriod = 'DD';
        cccforceAll = true;

        var i, tablinks;

        tablinks = document.getElementsByClassName('tabperiods');
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(' tabperiods_active', '');
        }
        if (event.currentTarget != undefined)
            event.currentTarget.className += ' tabperiods_active';

        cccUpdateChart();
    }
};

tabsPeriodsContainer.appendChild(tabPeriodElemALL);


optionsContainer.appendChild(tabsPeriodsContainer);
var separatorDivToGiveDivSize = document.createElement("div");
separatorDivToGiveDivSize.style.height = "0px";
separatorDivToGiveDivSize.style.clear = "both";

if (cccCurrentTheme.General.showExport) {
    /* Export Top */

    var exportBtnTop = document.createElement("div");
    exportBtnTop.className = 'exportBtnTop';
    exportBtnTop.innerText = 'Export';
    exportBtnTop.onclick = openLightBoxExport;
    cccCreateCSSSelector('.exportBtnTop', 'display: block; float: right; font-size: 18px; height: 40px; line-height: 40px; background: rgb(255, 205, 4); width: 120px; text-align: center; border-radius: 20px;');
    cccCreateCSSSelector('.exportBtnTop:hover', 'cursor: pointer; color: rgb(255, 205, 4); background: #000');
    cccCreateCSSSelector('@media (max-width: 767px)', '.exportBtnTop { display: none; }');

    optionsContainer.appendChild(exportBtnTop);
    optionsContainer.appendChild(separatorDivToGiveDivSize);

    /* Main append */

    embedableInfo.appendChild(optionsContainer);

    embedableInfo.appendChild(containerCanvas);

    /* Export Bottom */

    var exportBtnBottom = document.createElement("div");
    exportBtnBottom.className = 'exportBtnBottom';
    exportBtnBottom.innerText = 'Export';
    exportBtnBottom.onclick = openLightBoxExport;

    cccCreateCSSSelector('.exportBtnBottom', 'margin: 15px auto; margin-bottom: 0px; display: none; font-size: 18px; height: 40px; line-height: 40px; background: rgb(255, 205, 4); width: 120px; text-align: center; border-radius: 20px;');
    cccCreateCSSSelector('.exportBtnBottom:hover', 'cursor: pointer; color: rgb(255, 205, 4); background: #000');
    cccCreateCSSSelector('@media (max-width: 767px)', '.exportBtnBottom { display: block; }');

    embedableInfo.appendChild(exportBtnBottom);
} else {
    optionsContainer.appendChild(separatorDivToGiveDivSize);
    embedableInfo.appendChild(optionsContainer);
    embedableInfo.appendChild(containerCanvas);
}
/* Loading */

cccCreateCSSSelector('.loader-ccc', 'display: none; position: absolute; width: 120px; height: 120px; top: 50%; left: 50%; margin-left: -60px; margin-top: -60px;');
cccCreateCSSSelector('.loader-ccc-logo', 'position: absolute; background: #FFF url(\'\') center no-repeat; left: 20px; right: 20px; top: 20px; bottom: 20px; border-radius: 50%; z-index: 5; border: 1px solid #49D87C;');
cccCreateCSSSelector('.loader-ccc-sides', 'position: relative; width: 120px; height: 120px; animation: loader-ccc-sides 1.5s infinite linear; border-radius: 50%;');
cccCreateCSSSelector('.loader-ccc-sides:after', 'position: absolute; width: 120px; height: 120px; border-top: 10px solid #49D87C; border-bottom: 10px solid #49D87C; border-left: 10px solid transparent; border-right: 10px solid transparent; border-radius: 50%; content: \'\'; top: 0; left: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; ');
cccCreateCSSSelector('@keyframes loader-ccc-sides', '0% {transform: rotate(0deg);} 50% {transform: rotate(180deg);} 100% {transform: rotate(360deg);}');


var loaderccc = document.createElement("div");
var loaderccclogo = document.createElement("div");
var loadercccsides = document.createElement("div");

loaderccc.id = 'loaderccc';
loaderccc.className = 'loader-ccc';
loaderccclogo.className = 'loader-ccc-logo';
loadercccsides.className = 'loader-ccc-sides';

loaderccc.appendChild(loaderccclogo);
loaderccc.appendChild(loadercccsides);

embedableInfo.appendChild(loaderccc);

embedable.appendChild(embedableInfo);


var monthShort = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
Date.prototype.monthDayHourMinute = function () {
    var month = monthShort[this.getMonth()];
    var dd = this.getDate().toString();
    var hh = this.getHours().toString();
    var minute = this.getMinutes().toString();

    return month + " " + (dd[1] ? dd : "0" + dd[0]) + " , " + (hh[1] ? hh : "0" + hh[0]) + ":" + (minute[1] ? minute : "0" + minute[0]);
};

Date.prototype.monthDayYear = function () {
    var month = monthShort[this.getMonth()];
    var dd = this.getDate().toString();
    var yyyy = this.getFullYear().toString();

    return month + " " + (dd[1] ? dd : "0" + dd[0]) + " , " + yyyy;
};

Date.prototype.yearMonthDay = function () {
    var month = monthShort[this.getMonth()];
    var dd = this.getDate().toString();
    var yyyy = this.getFullYear().toString();

    return yyyy + "-" + month + "-" + (dd[1] ? dd : "0" + dd[0]);
};

document.getElementById("bitcoin").appendChild(embedable)
// document.currentScript.parentNode.appendChild(embedable);

$(tabPeriodElem1M).click();